// network.cpp : Defines the entry point for the DLL application.
//


#include "stdafx.h"

#include <stdlib.h>
#include <winsock2.h>

#include "bufchain.h"


#include <WS2tcpip.h>
#include "network.h"

enum {
    /*
     * Network address types. Used for specifying choice of IPv4/v6
     * in config; also used in proxy.c to indicate whether a given
     * host name has already been resolved or will be resolved at
     * the proxy end.
     */
    ADDRTYPE_UNSPEC, ADDRTYPE_IPV4, ADDRTYPE_IPV6, ADDRTYPE_NAME
};

#ifndef DONE_TYPEDEFS
#define DONE_TYPEDEFS
#endif



#ifndef OSSOCKET_DEFINED
typedef void *OSSocket;
#endif


struct SockAddr_tag {
    wchar_t *error;
    /* 
     * Which address family this address belongs to. AF_INET for
     * IPv4; AF_INET6 for IPv6; AF_UNSPEC indicates that name
     * resolution has not been done and a simple host name is held
     * in this SockAddr structure.
     * The hostname field is also used when the hostname has both
     * an IPv6 and IPv4 address and the IPv6 connection attempt
     * fails. We then try the IPv4 address.
     * This 'family' should become an option in the GUI and
     * on the commandline for selecting a default protocol.
     */
    int family;
#ifndef NO_IPV6
    struct addrinfo *ais;	       /* Addresses IPv6 style. */
    struct addrinfo *ai;	       /* steps along the linked list */
#endif
    unsigned long *addresses;	       /* Addresses IPv4 style. */
    int naddresses, curraddr;
    wchar_t hostname[512];		       /* Store an unresolved host name. */
};



/* pay attention to levels of indirection */


struct socket_function_table {
    /* use a different plug (return the old one) */
    /* if p is NULL, it doesn't change the plug */
    /* but it does return the one it's using */
    void (*close) (Socket s);
    int (*write) (Socket s, char *data, int len);
    int (*write_oob) (Socket s, char *data, int len);
    void (*flush) (Socket s);
    void (*set_private_ptr) (Socket s, void *ptr);
    void *(*get_private_ptr) (Socket s);
    void (*set_frozen) (Socket s, int is_frozen);
    /* ignored by tcp, but vital for ssl */
    wchar_t *(*socket_error) (Socket s);
};

struct Socket_tag {
    const struct socket_function_table *fn;
    /* the above variable absolutely *must* be the first in this structure */
    wchar_t *error;
    SOCKET s;
    Plug plug;
    void *private_ptr;
    bufchain output_data;
    int connected;
    int writable;
    int frozen; /* this causes readability notifications to be ignored */
    int frozen_readable; /* this means we missed at least one readability
			  * notification while we were frozen */
    int localhost_only;		       /* for listening sockets */
    char oobdata[1];
    int sending_oob;
    int oobinline, nodelay, keepalive, privport;
    SockAddr addr;
    int port;
    int pending_error;		       /* in case send() returns error */
	WPARAM wParam;
	HWND hwnd;
};


/* socket functions */

void sk_init(void);		       /* called once at program startup */
void sk_cleanup(void);		       /* called just before program exit */

SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family);
int sk_hostname_is_local(char *name);
int sk_address_is_local(SockAddr addr);
int sk_addrtype(SockAddr addr);
void sk_addrcopy(SockAddr addr, char *buf);

#ifdef __cplusplus    // If used by C++ code, 
extern "C" {          // we need to export the C interface
#endif

__declspec(dllexport) Actual_Socket new_connection(SockAddr addr, 
		      int port, int privport,
		      int oobinline, int nodelay, int keepalive,
		      Plug plug, HWND hwnd, WPARAM app_param);

__declspec(dllexport) void sk_addr_free(SockAddr addr);

__declspec(dllexport) void sk_getaddr(SockAddr addr, wchar_t *buf, int buflen);

#ifdef __cplusplus
}
#endif

DWORD try_connect(Actual_Socket sock);


/* NB, control of 'addr' is passed via sk_new, which takes responsibility
 * for freeing it, as for new_connection() */

#define sk_write_oob(s,buf,len, h) (((*s)->write_oob) (s, buf, len, h))
#define sk_flush(s) (((*s)->flush) (s))
#define sk_set_private_ptr(s, ptr) (((*s)->set_private_ptr) (s, ptr))
#define sk_get_private_ptr(s) (((*s)->get_private_ptr) (s))

#ifdef DEFINE_PLUG_METHOD_MACROS
#define plug_log(p,type,addr,port,msg,code) (((*p)->log) (p, type, addr, port, msg, code))
#define plug_closing(p,msg,code,callback) (((*p)->closing) (p, msg, code, callback))
#define plug_receive(p,urgent,buf,len) (((*p)->receive) (p, urgent, buf, len))
#define plug_sent(p,bufsize) (((*p)->sent) (p, bufsize))
#define plug_accepting(p, sock) (((*p)->accepting)(p, sock))
#endif

/*
 * Each socket abstraction contains a `void *' private field in
 * which the client can keep state.
 *
 * This is perhaps unnecessary now that we have the notion of a plug,
 * but there is some existing code that uses it, so it stays.
 */
#define sk_set_private_ptr(s, ptr) (((*s)->set_private_ptr) (s, ptr))
#define sk_get_private_ptr(s) (((*s)->get_private_ptr) (s))

/*
 * Set the `frozen' flag on a socket. A frozen socket is one in
 * which all READABLE notifications are ignored, so that data is
 * not accepted from the peer until the socket is unfrozen. This
 * exists for two purposes:
 * 
 *  - Port forwarding: when a local listening port receives a
 *    connection, we do not want to receive data from the new
 *    socket until we have somewhere to send it. Hence, we freeze
 *    the socket until its associated SSH channel is ready; then we
 *    unfreeze it and pending data is delivered.
 * 
 *  - Socket buffering: if an SSH channel (or the whole connection)
 *    backs up or presents a zero window, we must freeze the
 *    associated local socket in order to avoid unbounded buffer
 *    growth.
 */


/*
 * Simple wrapper on getservbyname(), needed by ssh.c. Returns the
 * port number, in host byte order (suitable for printf and so on).
 * Returns 0 on failure. Any platform not supporting getservbyname
 * can just return 0 - this function is not required to handle
 * numeric port specifications.
 */
int net_service_lookup(char *service);


#define NOTHING
#define DECL_WINSOCK_FUNCTION(linkage, rettype, name, params) \
    typedef rettype (WINAPI *t_##name) params; \
    linkage t_##name p_##name
#define GET_WINSOCK_FUNCTION(module, name) \
    p_##name = module ? (t_##name) GetProcAddress(module, #name) : NULL


#define ipv4_is_loopback(addr) \
	((p_ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L)
int sk_address_is_local(SockAddr addr);
int sk_hostname_is_local(wchar_t *name);
void sk_getaddr(SockAddr addr, LPTSTR buf, int buflen);
int ipv4_is_local_addr(struct in_addr addr);

Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
	      int nodelay, int keepalive, Plug plug, HWND hwnd);


void sk_tcp_close(Socket s);
int sk_tcp_write(Socket s, char *data, int len);
int sk_tcp_write_oob(Socket s, char *data, int len);
void sk_tcp_set_private_ptr(Socket s, void *ptr);
void *sk_tcp_get_private_ptr(Socket s);
void sk_tcp_set_frozen(Socket s, int is_frozen);
wchar_t *sk_tcp_socket_error(Socket s);
void sk_tcp_flush(Socket s);

SockAddr sk_nonamelookup(wchar_t *host);


#define plug_log(p,type,addr,port,msg,code) (((*p->plug)->log) ((Socket)p, type, addr, port, msg, code, p->wParam))
#define plug_closing(p, msg,code,callback) (((*p->plug)->closing) ((Socket)p, msg, code, callback, p->wParam))
#define plug_receive(p,urgent,buf,len) (((*p->plug)->receive) ((Socket)p, urgent, buf, len, p->wParam))
#define plug_sent(p,bufsize) (((*p->plug)->sent) ((Socket)p, bufsize, p->wParam))

#define lenof(x) ( sizeof((x)) / sizeof(*(x)) )


DECL_WINSOCK_FUNCTION(NOTHING, int, WSAAsyncSelect,
		      (SOCKET, HWND, u_int, long));
DECL_WINSOCK_FUNCTION(NOTHING, int, WSAEventSelect, (SOCKET, WSAEVENT, long));
DECL_WINSOCK_FUNCTION(NOTHING, int, select,
		      (int, fd_set FAR *, fd_set FAR *,
		       fd_set FAR *, const struct timeval FAR *));
DECL_WINSOCK_FUNCTION(NOTHING, int, WSAGetLastError, (void));
DECL_WINSOCK_FUNCTION(NOTHING, int, WSAEnumNetworkEvents,
		      (SOCKET, WSAEVENT, LPWSANETWORKEVENTS));
DECL_WINSOCK_FUNCTION(static, int, WSAStartup, (WORD, LPWSADATA));
DECL_WINSOCK_FUNCTION(static, int, WSACleanup, (void));
DECL_WINSOCK_FUNCTION(static, int, closesocket, (SOCKET));
DECL_WINSOCK_FUNCTION(static, u_long, ntohl, (u_long));
DECL_WINSOCK_FUNCTION(static, u_long, htonl, (u_long));
DECL_WINSOCK_FUNCTION(static, u_short, htons, (u_short));
DECL_WINSOCK_FUNCTION(static, u_short, ntohs, (u_short));
DECL_WINSOCK_FUNCTION(static, struct hostent FAR *, gethostbyname,
		      (const char FAR *));
DECL_WINSOCK_FUNCTION(static, struct servent FAR *, getservbyname,
		      (const char FAR *, const char FAR *));
DECL_WINSOCK_FUNCTION(static, unsigned long, inet_addr, (const char FAR *));
DECL_WINSOCK_FUNCTION(static, char FAR *, inet_ntoa, (struct in_addr));
DECL_WINSOCK_FUNCTION(static, int, connect,
		      (SOCKET, const struct sockaddr FAR *, int));
DECL_WINSOCK_FUNCTION(static, int, bind,
		      (SOCKET, const struct sockaddr FAR *, int));
DECL_WINSOCK_FUNCTION(static, int, setsockopt,
		      (SOCKET, int, int, const char FAR *, int));
DECL_WINSOCK_FUNCTION(static, SOCKET, socket, (int, int, int));
DECL_WINSOCK_FUNCTION(static, int, listen, (SOCKET, int));
DECL_WINSOCK_FUNCTION(static, int, send, (SOCKET, const char FAR *, int, int));
DECL_WINSOCK_FUNCTION(static, int, ioctlsocket,
		      (SOCKET, long, u_long FAR *));
DECL_WINSOCK_FUNCTION(static, SOCKET, accept,
		      (SOCKET, struct sockaddr FAR *, int FAR *));
DECL_WINSOCK_FUNCTION(static, int, recv, (SOCKET, char FAR *, int, int));
DECL_WINSOCK_FUNCTION(static, int, WSAIoctl,
		      (SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD,
		       LPDWORD, LPWSAOVERLAPPED,
		       LPWSAOVERLAPPED_COMPLETION_ROUTINE));
#ifndef NO_IPV6
DECL_WINSOCK_FUNCTION(static, int, getaddrinfo,
		      (const char *nodename, const wchar_t *servname,
		       const struct addrinfo *hints, struct addrinfo **res));
DECL_WINSOCK_FUNCTION(static, void, freeaddrinfo, (struct addrinfo *res));
DECL_WINSOCK_FUNCTION(static, int, getnameinfo,
		      (const struct sockaddr FAR * sa, socklen_t salen,
		       char FAR * host, size_t hostlen, char FAR * serv,
		       size_t servlen, int flags));
DECL_WINSOCK_FUNCTION(static, wchar_t *, gai_strerror, (int ecode));
DECL_WINSOCK_FUNCTION(static, int, WSAAddressToStringW,
		      (LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFO,
		       LPTSTR, LPDWORD));
#endif

SockAddr sk_namelookup(const char *host, char **canonicalname,
		       int address_family)
{
    SockAddr ret = new SockAddr_tag;
    unsigned long a;
    struct hostent *h = NULL;
    char realhost[8192];
    int ret_family;
    int err;

    /* Clear the structure and default to IPv4. */
    memset(ret, 0, sizeof(struct SockAddr_tag));
    ret->family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
#ifndef NO_IPV6
		   address_family == ADDRTYPE_IPV6 ? AF_INET6 :
#endif
		   AF_UNSPEC);
#ifndef NO_IPV6
    ret->ai = ret->ais = NULL;
#endif
    ret->addresses = NULL;
    ret_family = AF_UNSPEC;
    *realhost = '\0';

	if ((a = p_inet_addr(host)) == (unsigned long) INADDR_NONE) {
#ifndef NO_IPV6
	/*
	 * Use getaddrinfo when it's available
	 */
	if (p_getaddrinfo) {
	    struct addrinfo hints;
#ifdef NET_SETUP_DIAGNOSTICS
	    MessageBox(NULL, L"Using getaddrinfo() for resolving");
#endif
	    memset(&hints, 0, sizeof(hints));
	    hints.ai_family = ret->family;
	    hints.ai_flags = AI_CANONNAME;
	    if ((err = p_getaddrinfo(host, NULL, &hints, &ret->ais)) == 0)
		ret_family = ret->ais->ai_family;
	    ret->ai = ret->ais;
	} else
#endif
	{
#ifdef NET_SETUP_DIAGNOSTICS
	    MessageBox(NULL, L"Using gethostbyname() for resolving");
#endif
	    /*
	     * Otherwise use the IPv4-only gethostbyname...
	     * (NOTE: we don't use gethostbyname as a fallback!)
	     */
	    if ( (h = p_gethostbyname(host)) )
		ret_family = AF_INET;
	    else
		err = p_WSAGetLastError();
	}

	if (ret_family == AF_UNSPEC) {
	    ret->error = (err == WSAENETDOWN ? L"Network is down" :
			  err == WSAHOST_NOT_FOUND ? L"Host does not exist" :
			  err == WSATRY_AGAIN ? L"Host not found" :
#ifndef NO_IPV6
			  p_getaddrinfo&&p_gai_strerror ? p_gai_strerror(err) :
#endif
			  L"gethostbyname: unknown error");
	} else {
	    ret->error = NULL;
	    ret->family = ret_family;

#ifndef NO_IPV6
	    /* If we got an address info use that... */
	    if (ret->ai) {
		/* Are we in IPv4 fallback mode? */
		/* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
		if (ret->family == AF_INET)
		    memcpy(&a,
			   (char *) &((SOCKADDR_IN *) ret->ai->
				      ai_addr)->sin_addr, sizeof(a));
		if (ret->ai->ai_canonname)
		    strcpy(realhost,ret->ai->ai_canonname);
		else
		    strcpy(realhost,host);
	    }
	    /* We used the IPv4-only gethostbyname()... */
	    else
#endif
	    {
		int n;
		for (n = 0; h->h_addr_list[n]; n++);
		ret->addresses = new unsigned long[n];
		ret->naddresses = n;
		for (n = 0; n < ret->naddresses; n++) {
		    memcpy(&a, h->h_addr_list[n], sizeof(a));
		    ret->addresses[n] = p_ntohl(a);
		}
		ret->curraddr = 0;
		memcpy(&a, h->h_addr, sizeof(a));
		/* This way we are always sure the h->h_name is valid :) */
		strcpy(realhost, h->h_name);
	    }
	}
    } else {
	/*
	 * This must be a numeric IPv4 address because it caused a
	 * success return from inet_addr.
	 */
	ret->addresses = new unsigned long;
	ret->naddresses = 1;
	ret->curraddr = 0;
	ret->addresses[0] = p_ntohl(a);
	ret->family = AF_INET;
	strcpy(realhost, host);
    }
    realhost[lenof(realhost)-1] = '\0';
    *canonicalname = new char[1+strlen(realhost)];
    strcpy(*canonicalname, realhost);
    return ret;
}





wchar_t *winsock_error_string(int error)
{
    switch (error) {
      case WSAEACCES:
	return L"Network error: Permission denied";
      case WSAEADDRINUSE:
	return L"Network error: Address already in use";
      case WSAEADDRNOTAVAIL:
	return L"Network error: Cannot assign requested address";
      case WSAEAFNOSUPPORT:
	return
	    L"Network error: Address family not supported by protocol family";
      case WSAEALREADY:
	return L"Network error: Operation already in progress";
      case WSAECONNABORTED:
	return L"Network error: Software caused connection abort";
      case WSAECONNREFUSED:
	return L"Network error: Connection refused";
      case WSAECONNRESET:
	return L"Network error: Connection reset by peer";
      case WSAEDESTADDRREQ:
	return L"Network error: Destination address required";
      case WSAEFAULT:
	return L"Network error: Bad address";
      case WSAEHOSTDOWN:
	return L"Network error: Host is down";
      case WSAEHOSTUNREACH:
	return L"Network error: No route to host";
      case WSAEINPROGRESS:
	return L"Network error: Operation now in progress";
      case WSAEINTR:
	return L"Network error: Interrupted function call";
      case WSAEINVAL:
	return L"Network error: Invalid argument";
      case WSAEISCONN:
	return L"Network error: Socket is already connected";
      case WSAEMFILE:
	return L"Network error: Too many open files";
      case WSAEMSGSIZE:
	return L"Network error: Message too long";
      case WSAENETDOWN:
	return L"Network error: Network is down";
      case WSAENETRESET:
	return L"Network error: Network dropped connection on reset";
      case WSAENETUNREACH:
	return L"Network error: Network is unreachable";
      case WSAENOBUFS:
	return L"Network error: No buffer space available";
      case WSAENOPROTOOPT:
	return L"Network error: Bad protocol option";
      case WSAENOTCONN:
	return L"Network error: Socket is not connected";
      case WSAENOTSOCK:
	return L"Network error: Socket operation on non-socket";
      case WSAEOPNOTSUPP:
	return L"Network error: Operation not supported";
      case WSAEPFNOSUPPORT:
	return L"Network error: Protocol family not supported";
      case WSAEPROCLIM:
	return L"Network error: Too many processes";
      case WSAEPROTONOSUPPORT:
	return L"Network error: Protocol not supported";
      case WSAEPROTOTYPE:
	return L"Network error: Protocol wrong type for socket";
      case WSAESHUTDOWN:
	return L"Network error: Cannot send after socket shutdown";
      case WSAESOCKTNOSUPPORT:
	return L"Network error: Socket type not supported";
      case WSAETIMEDOUT:
	return L"Network error: Connection timed out";
      case WSAEWOULDBLOCK:
	return L"Network error: Resource temporarily unavailable";
      case WSAEDISCON:
	return L"Network error: Graceful shutdown in progress";
      default:
	return L"Unknown network error";
    }
}


wchar_t *do_select(SOCKET skt, int startup, HWND hwnd)
{
    int msg, events;
    if (startup) {
	msg = WM_NETEVENT;
	events = (FD_CONNECT | FD_READ | FD_WRITE |
		  FD_OOB | FD_CLOSE | FD_ACCEPT);
    } else {
	msg = events = 0;
    }
    if (!hwnd)
	return L"do_select(): internal error (hwnd==NULL)";
    if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
	switch (p_WSAGetLastError()) {
	  case WSAENETDOWN:
	    return L"Network is down";
	  default:
	    return L"WSAAsyncSelect(): unknown error";
	}
    }
    return NULL;
}





void sk_tcp_flush(Socket s)
{
    /*
     * We send data to the socket as soon as we can anyway,
     * so we don't need to do anything here.  :-)
     */
}
void try_send(Actual_Socket s)
{
    while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
	int nsent;
	DWORD err;
	void *data;
	int len, urgentflag;

	if (s->sending_oob) {
	    urgentflag = MSG_OOB;
	    len = s->sending_oob;
	    data = &s->oobdata;
	} else {
	    urgentflag = 0;
	    bufchain_prefix(&s->output_data, &data, &len);
	}
	nsent = p_send(s->s, (const char*)data, len, urgentflag);
	if (nsent <= 0) {
	    err = (nsent < 0 ? p_WSAGetLastError() : 0);
	    if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
		/*
		 * Perfectly normal: we've sent all we can for the moment.
		 * 
		 * (Some WinSock send() implementations can return
		 * <0 but leave no sensible error indication -
		 * WSAGetLastError() is called but returns zero or
		 * a small number - so we check that case and treat
		 * it just like WSAEWOULDBLOCK.)
		 */
		s->writable = FALSE;
		return;
	    } else if (nsent == 0 ||
		       err == WSAECONNABORTED || err == WSAECONNRESET) {
		/*
		 * If send() returns CONNABORTED or CONNRESET, we
		 * unfortunately can't just call plug_closing(),
		 * because it's quite likely that we're currently
		 * _in_ a call from the code we'd be calling back
		 * to, so we'd have to make half the SSH code
		 * reentrant. Instead we flag a pending error on
		 * the socket, to be dealt with (by calling
		 * plug_closing()) at some suitable future moment.
		 */
		s->pending_error = err;
		return;
	    } else {
		/* We're inside the Windows frontend here, so we know
		 * that the frontend handle is unnecessary. */
		MessageBox(NULL, winsock_error_string(err), L"sshControl",MB_OK);
//		fatalbox("%s", winsock_error_string(err));
	    }
	} else {
	    if (s->sending_oob) {
		if (nsent < len) {
		    memmove(s->oobdata, s->oobdata+nsent, len-nsent);
		    s->sending_oob = len - nsent;
		} else {
		    s->sending_oob = 0;
		}
	    } else {
		bufchain_consume(&s->output_data, nsent);
	    }
	}
    }
}

int sk_tcp_write(Socket sock, char *buf, int len)
{
    Actual_Socket s = (Actual_Socket) sock;

    /*
     * Add the data to the buffer list on the socket.
     */
    bufchain_add(&s->output_data, buf, len);

    /*
     * Now try sending from the start of the buffer list.
     */
    if (s->writable)
	try_send(s);

    return bufchain_size(&s->output_data);
}

int sk_tcp_write_oob(Socket sock, char *buf, int len)
{
    Actual_Socket s = (Actual_Socket) sock;

    /*
     * Replace the buffer list on the socket with the data.
     */
    bufchain_clear(&s->output_data);
    memcpy(s->oobdata, buf, len);
    s->sending_oob = len;

    /*
     * Now try sending from the start of the buffer list.
     */
    if (s->writable)
	try_send(s);

    return s->sending_oob;
}
void sk_tcp_set_private_ptr(Socket sock, void *ptr)
{
    Actual_Socket s = (Actual_Socket) sock;
    s->private_ptr = ptr;
}

void *sk_tcp_get_private_ptr(Socket sock)
{
    Actual_Socket s = (Actual_Socket) sock;
    return s->private_ptr;
}

/*
 * Special error values are returned from sk_namelookup and sk_new
 * if there's a problem. These functions extract an error message,
 * or return NULL if there's no problem.
 */

wchar_t *sk_tcp_socket_error(Socket sock)
{
    Actual_Socket s = (Actual_Socket) sock;
    return s->error;
}

void sk_tcp_set_frozen(Socket sock, int is_frozen)
{
    Actual_Socket s = (Actual_Socket) sock;
    if (s->frozen == is_frozen)
	return;
    s->frozen = is_frozen;
    if (!is_frozen) {
	do_select(s->s, 1, s->hwnd);
	if (s->frozen_readable) {
	    char c;
	    p_recv(s->s, &c, 1, MSG_PEEK);
	}
    }
    s->frozen_readable = 0;
}

int sk_nextaddr(SockAddr addr)
{
#ifndef NO_IPV6
    if (addr->ai) {
	if (addr->ai->ai_next) {
	    addr->ai = addr->ai->ai_next;
	    addr->family = addr->ai->ai_family;
	    return TRUE;
	} else
	    return FALSE;
    }
#endif
    if (addr->curraddr+1 < addr->naddresses) {
	addr->curraddr++;
	return TRUE;
    } else {
	return FALSE;
    }
}


void sk_tcp_close(Socket sock)
{
    Actual_Socket s = (Actual_Socket) sock;

    do_select(s->s, 0, s->hwnd);
    p_closesocket(s->s);
    if (s->addr)
	sk_addr_free(s->addr);
    delete s;
}
DWORD try_connect(Actual_Socket sock)
{
    SOCKET s;
#ifndef NO_IPV6
    SOCKADDR_IN6 a6;
#endif
    SOCKADDR_IN a;
    DWORD err;
    wchar_t *errstr;
    short localport;
    int family;

    if (sock->s != INVALID_SOCKET) {
	do_select(sock->s, 0, sock->hwnd);
        p_closesocket(sock->s);
    }

    plug_log(sock, 0, sock->addr, sock->port, NULL, 0);

    /*
     * Open socket.
     */
#ifndef NO_IPV6
    /* Let's default to IPv6, this shouldn't hurt anybody
     * If the stack supports IPv6 it will also allow IPv4 connections. */
    if (sock->addr->ai) {
	family = sock->addr->ai->ai_family;
    } else
#endif
    {
	/* Default to IPv4 */
	family = AF_INET;
    }

    s = p_socket(family, SOCK_STREAM, 0);
    sock->s = s;

    if (s == INVALID_SOCKET) {
	err = p_WSAGetLastError();
	sock->error = winsock_error_string(err);
	goto ret;
    }

    if (sock->oobinline) {
	BOOL b = TRUE;
	p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (const char*) &b, sizeof(b));
    }

    if (sock->nodelay) {
	BOOL b = TRUE;
	p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const char*) &b, sizeof(b));
    }

    if (sock->keepalive) {
	BOOL b = TRUE;
	p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (const char*) &b, sizeof(b));
    }

    /*
     * Bind to local address.
     */
    if (sock->privport)
	localport = 1023;	       /* count from 1023 downwards */
    else
	localport = 0;		       /* just use port 0 (ie winsock picks) */

    /* Loop round trying to bind */
    while (1) {
	int sockcode;

#ifndef NO_IPV6
	if (family == AF_INET6) {
	    memset(&a6, 0, sizeof(a6));
	    a6.sin6_family = AF_INET6;
          /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */
	    a6.sin6_port = p_htons(localport);
	} else
#endif
	{
	    a.sin_family = AF_INET;
	    a.sin_addr.s_addr = p_htonl(INADDR_ANY);
	    a.sin_port = p_htons(localport);
	}
#ifndef NO_IPV6
	sockcode = p_bind(s, (sock->addr->family == AF_INET6 ?
			   (struct sockaddr *) &a6 :
			   (struct sockaddr *) &a),
		       (sock->addr->family ==
			AF_INET6 ? sizeof(a6) : sizeof(a)));
#else
	sockcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
#endif
	if (sockcode != SOCKET_ERROR) {
	    err = 0;
	    break;		       /* done */
	} else {
	    err = p_WSAGetLastError();
	    if (err != WSAEADDRINUSE)  /* failed, for a bad reason */
		break;
	}

	if (localport == 0)
	    break;		       /* we're only looping once */
	localport--;
	if (localport == 0)
	    break;		       /* we might have got to the end */
    }

    if (err) {
	sock->error = winsock_error_string(err);
	goto ret;
    }

    /*
     * Connect to remote address.
     */
#ifndef NO_IPV6
    if (sock->addr->ai) {
	if (family == AF_INET6) {
	    a6.sin6_family = AF_INET6;
	    a6.sin6_port = p_htons((short) sock->port);
	    a6.sin6_addr =
		((struct sockaddr_in6 *) sock->addr->ai->ai_addr)->sin6_addr;
	    a6.sin6_flowinfo = ((struct sockaddr_in6 *) sock->addr->ai->ai_addr)->sin6_flowinfo;
	    a6.sin6_scope_id = ((struct sockaddr_in6 *) sock->addr->ai->ai_addr)->sin6_scope_id;
	} else {
	    a.sin_family = AF_INET;
	    a.sin_addr =
		((struct sockaddr_in *) sock->addr->ai->ai_addr)->sin_addr;
	    a.sin_port = p_htons((short) sock->port);
	}
    } else
#endif
    {
	a.sin_family = AF_INET;
	a.sin_addr.s_addr = p_htonl(sock->addr->addresses[sock->addr->curraddr]);
	a.sin_port = p_htons((short) sock->port);
    }

    /* Set up a select mechanism. This could be an AsyncSelect on a
     * window, or an EventSelect on an event object. */
    errstr = do_select(s, 1, sock->hwnd);
    if (errstr) {
	sock->error = errstr;
	err = 1;
	goto ret;
    }

    if ((
#ifndef NO_IPV6
	    p_connect(s,
		      ((family == AF_INET6) ? (struct sockaddr *) &a6 :
		       (struct sockaddr *) &a),
		      (family == AF_INET6) ? sizeof(a6) : sizeof(a))
#else
	    p_connect(s, (struct sockaddr *) &a, sizeof(a))
#endif
	) == SOCKET_ERROR) {
	err = p_WSAGetLastError();
	/*
	 * We expect a potential EWOULDBLOCK here, because the
	 * chances are the front end has done a select for
	 * FD_CONNECT, so that connect() will complete
	 * asynchronously.
	 */
	if ( err != WSAEWOULDBLOCK ) {
	    sock->error = winsock_error_string(err);
	    goto ret;
	}
    } else {
	/*
	 * If we _don't_ get EWOULDBLOCK, the connect has completed
	 * and we should set the socket as writable.
	 */
	sock->writable = 1;
    }

    err = 0;

    ret:
    if (err)
	plug_log(sock, 1, sock->addr, sock->port, sock->error, err);
    return err;
}


Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
	      int nodelay, int keepalive, Plug plug, HWND hwnd, WPARAM param)
{
    static const struct socket_function_table fn_table = {
	sk_tcp_close,
	sk_tcp_write,
	sk_tcp_write_oob,
	sk_tcp_flush,
	sk_tcp_set_private_ptr,
	sk_tcp_get_private_ptr,
	sk_tcp_set_frozen,
	sk_tcp_socket_error
    };

    Actual_Socket ret;
    DWORD err;

    /*
     * Create Socket structure.
     */
    ret = new Socket_tag;
    ret->fn = &fn_table;
    ret->error = NULL;
    ret->plug = plug;
    bufchain_init(&ret->output_data);
    ret->connected = 0;		       /* to start with */
    ret->writable = 0;		       /* to start with */
    ret->sending_oob = 0;
    ret->frozen = 0;
    ret->frozen_readable = 0;
    ret->localhost_only = 0;	       /* unused, but best init anyway */
    ret->pending_error = 0;
    ret->oobinline = oobinline;
    ret->nodelay = nodelay;
    ret->keepalive = keepalive;
    ret->privport = privport;
    ret->port = port;
    ret->addr = addr;
    ret->s = INVALID_SOCKET;
	ret->wParam=param;
	ret->hwnd=hwnd;

    err = 0;
    do {
        err = try_connect(ret);
    } while (err && sk_nextaddr(ret->addr));

    return (Socket) ret;
}








int defined=0;
static HMODULE winsock_module = NULL;
static WSADATA wsadata;
#ifndef NO_IPV6
static HMODULE winsock2_module = NULL;
static HMODULE wship6_module = NULL;
#endif


int sk_startup(int hi, int lo)
{
    WORD winsock_ver;

    winsock_ver = MAKEWORD(hi, lo);

    if (p_WSAStartup(winsock_ver, &wsadata)) {
	return FALSE;
    }

    if (LOBYTE(wsadata.wVersion) != LOBYTE(winsock_ver)) {
	return FALSE;
    }

    return TRUE;
}


void sk_init()
{
	if (defined==0) {
#ifndef NO_IPV6
    winsock2_module =
#endif
        winsock_module = LoadLibrary(L"WS2_32.DLL");
    if (!winsock_module) {
	winsock_module = LoadLibrary(L"WSOCK32.DLL");
    }
	if (!winsock_module) {
		MessageBox(NULL,L"Error loading Winsock.dll: file not found or unable to initialize",L"Windows sockets",MB_OK);
		return;
	}

#ifndef NO_IPV6
    /* Check if we have getaddrinfo in Winsock */
    if (GetProcAddress(winsock_module, (LPCSTR)L"getaddrinfo") != NULL) {
#ifdef NET_SETUP_DIAGNOSTICS
	MessageBox(NULL, L"Native WinSock IPv6 support detected");
#endif
	GET_WINSOCK_FUNCTION(winsock_module, getaddrinfo);
	GET_WINSOCK_FUNCTION(winsock_module, freeaddrinfo);
	GET_WINSOCK_FUNCTION(winsock_module, getnameinfo);
	GET_WINSOCK_FUNCTION(winsock_module, gai_strerror);
    } else {
	/* Fall back to wship6.dll for Windows 2000 */
	wship6_module = LoadLibrary(L"wship6.dll");
	if (wship6_module) {
#ifdef NET_SETUP_DIAGNOSTICS
	    MessageBox(NULL, L"WSH IPv6 support detected");
#endif
	    GET_WINSOCK_FUNCTION(wship6_module, getaddrinfo);
	    GET_WINSOCK_FUNCTION(wship6_module, freeaddrinfo);
	    GET_WINSOCK_FUNCTION(wship6_module, getnameinfo);
	    GET_WINSOCK_FUNCTION(wship6_module, gai_strerror);
	} else {
#ifdef NET_SETUP_DIAGNOSTICS
	    MessageBox(NULL, L"No IPv6 support detected");
#endif
	}
    }
    GET_WINSOCK_FUNCTION(winsock2_module, WSAAddressToStringW);
#else
#ifdef NET_SETUP_DIAGNOSTICS
    MessageBox(NULL, L"PuTTY was built without IPv6 support");
#endif
#endif

    GET_WINSOCK_FUNCTION(winsock_module, WSAAsyncSelect);
    GET_WINSOCK_FUNCTION(winsock_module, WSAEventSelect);
    GET_WINSOCK_FUNCTION(winsock_module, select);
    GET_WINSOCK_FUNCTION(winsock_module, WSAGetLastError);
    GET_WINSOCK_FUNCTION(winsock_module, WSAEnumNetworkEvents);
    GET_WINSOCK_FUNCTION(winsock_module, WSAStartup);
    GET_WINSOCK_FUNCTION(winsock_module, WSACleanup);
    GET_WINSOCK_FUNCTION(winsock_module, closesocket);
    GET_WINSOCK_FUNCTION(winsock_module, ntohl);
    GET_WINSOCK_FUNCTION(winsock_module, htonl);
    GET_WINSOCK_FUNCTION(winsock_module, htons);
    GET_WINSOCK_FUNCTION(winsock_module, ntohs);
    GET_WINSOCK_FUNCTION(winsock_module, gethostbyname);
    GET_WINSOCK_FUNCTION(winsock_module, getservbyname);
    GET_WINSOCK_FUNCTION(winsock_module, inet_addr);
    GET_WINSOCK_FUNCTION(winsock_module, inet_ntoa);
    GET_WINSOCK_FUNCTION(winsock_module, connect);
    GET_WINSOCK_FUNCTION(winsock_module, bind);
    GET_WINSOCK_FUNCTION(winsock_module, setsockopt);
    GET_WINSOCK_FUNCTION(winsock_module, socket);
    GET_WINSOCK_FUNCTION(winsock_module, listen);
    GET_WINSOCK_FUNCTION(winsock_module, send);
    GET_WINSOCK_FUNCTION(winsock_module, ioctlsocket);
    GET_WINSOCK_FUNCTION(winsock_module, accept);
    GET_WINSOCK_FUNCTION(winsock_module, recv);
    GET_WINSOCK_FUNCTION(winsock_module, WSAIoctl);

    /* Try to get the best WinSock version we can get */
    if (!sk_startup(2,2) &&
	!sk_startup(2,0) &&
	!sk_startup(1,1)) {
		MessageBox(NULL,L"Error initializing Windows sockets: version not found",L"Windows sockets",MB_OK);
    }
	}
	defined=1;
}

int n_local_interfaces;
INTERFACE_INFO local_interfaces[16];

void sk_cleanup(void)
{
    p_WSACleanup();
    if (winsock_module)
	FreeLibrary(winsock_module);
#ifndef NO_IPV6
    if (wship6_module)
	FreeLibrary(wship6_module);
#endif
}

int ipv4_is_local_addr(struct in_addr addr)
{
    if (ipv4_is_loopback(addr))
	return 1;		       /* loopback addresses are local */
	if (!n_local_interfaces) {
	SOCKET s = p_socket(AF_INET, SOCK_DGRAM, 0);
	DWORD retbytes;

	if (p_WSAIoctl &&
	    p_WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0,
		       local_interfaces, sizeof(local_interfaces),
		       &retbytes, NULL, NULL) == 0)
	    n_local_interfaces = retbytes / sizeof(INTERFACE_INFO);
	else
	   MessageBox(NULL, L"Unable to get list of local IP addresses", L"Windows sockets",MB_OK);
    }
    if (n_local_interfaces > 0) {
	int i;
	for (i = 0; i < n_local_interfaces; i++) {
	    SOCKADDR_IN *address =
		(SOCKADDR_IN *)&local_interfaces[i].iiAddress;
	    if (address->sin_addr.s_addr == addr.s_addr)
		return 1;	       /* this address is local */
	}
    }
    return 0;		       /* this address is not local */
}

#ifdef __cplusplus    // If used by C++ code, 
extern "C" {          // we need to export the C interface
#endif


__declspec(dllexport) SockAddr name_lookup(char *host, int port, char **canonicalname,
		    int addressfamily)
{

    return sk_namelookup(host, canonicalname, addressfamily);
}

__declspec(dllexport) Actual_Socket new_connection(SockAddr addr,
		      int port, int privport,
		      int oobinline, int nodelay, int keepalive,
		      Plug plug, HWND hwnd, WPARAM app_param)
{
    
       /* no proxy, so just return the direct socket */
    return (Actual_Socket)sk_new(addr, port, privport, oobinline, nodelay, keepalive, plug, hwnd, app_param);
}

__declspec(dllexport) int select_result(WPARAM wParam, LPARAM lParam, Actual_Socket s)
{
    int ret, open;
    DWORD err;
    char buf[20480];		       /* nice big buffer for plenty of speed */
    u_long atmark;

    /* wParam is the socket itself */

    if (wParam == 0)
	return 1;		       /* boggle */

    if (!s)
	return 1;		       /* boggle */

    if ((err = WSAGETSELECTERROR(lParam)) != 0) {
	/*
	 * An error has occurred on this socket. Pass it to the
	 * plug.
	 */
	if (s->addr) {
	    plug_log(s, 1, s->addr, s->port,
		     winsock_error_string(err), err);
	    while (s->addr && sk_nextaddr(s->addr)) {
		err = try_connect(s);
	    }
	}
	if (err != 0)
	    return plug_closing(s, winsock_error_string(err), err, 0);
	else
	    return 1;
    }

    switch (WSAGETSELECTEVENT(lParam)) {
      case FD_CONNECT:
	s->connected = s->writable = 1;
	/*
	 * Once a socket is connected, we can stop falling
	 * back through the candidate addresses to connect
	 * to.
	 */
	if (s->addr) {
	    sk_addr_free(s->addr);
	    s->addr = NULL;
	}
	break;
      case FD_READ:
	/* In the case the socket is still frozen, we don't even bother */
	if (s->frozen) {
	    s->frozen_readable = 1;
	    break;
	}

	/*
	 * We have received data on the socket. For an oobinline
	 * socket, this might be data _before_ an urgent pointer,
	 * in which case we send it to the back end with type==1
	 * (data prior to urgent).
	 */
	if (s->oobinline) {
	    atmark = 1;
	    p_ioctlsocket(s->s, SIOCATMARK, &atmark);
	    /*
	     * Avoid checking the return value from ioctlsocket(),
	     * on the grounds that some WinSock wrappers don't
	     * support it. If it does nothing, we get atmark==1,
	     * which is equivalent to `no OOB pending', so the
	     * effect will be to non-OOB-ify any OOB data.
	     */
	} else
	    atmark = 1;

	ret = p_recv(s->s, buf, sizeof(buf), 0);
	if (ret < 0) {
	    err = p_WSAGetLastError();
	    if (err == WSAEWOULDBLOCK) {
		break;
	    }
	}
	if (ret < 0) {
	    return plug_closing(s, winsock_error_string(err), err,
				0);
	} else if (0 == ret) {
		return plug_closing(s, NULL, 0, 0);
	} else {
		return plug_receive(s, atmark ? 0 : 1, buf, ret);
	}
	break;
      case FD_OOB:
	/*
	 * This will only happen on a non-oobinline socket. It
	 * indicates that we can immediately perform an OOB read
	 * and get back OOB data, which we will send to the back
	 * end with type==2 (urgent data).
	 */
	ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
	if (ret <= 0) {
	    wchar_t *str = (ret == 0 ? L"Internal networking trouble" :
			 winsock_error_string(p_WSAGetLastError()));
	    /* We're inside the Windows frontend here, so we know
	     * that the frontend handle is unnecessary. */
//	    logevent(NULL, str);
//	    fatalbox("%s", str);
	} else {
	    return plug_receive(s, 2, buf, ret);
	}
	break;
      case FD_WRITE:
	{
	    int bufsize_before, bufsize_after;
	    s->writable = 1;
	    bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
	    try_send(s);
	    bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
	    if (bufsize_after < bufsize_before)
		plug_sent(s, bufsize_after);
	}
	break;
      case FD_CLOSE:
	/* Signal a close on the socket. First read any outstanding data. */
	open = 1;
	do {
	    ret = p_recv(s->s, buf, sizeof(buf), 0);
	    if (ret < 0) {
		err = p_WSAGetLastError();
		if (err == WSAEWOULDBLOCK)
		    break;
		return plug_closing(s, winsock_error_string(err),
				    err, 0);
	    } else {
		if (ret)
		    open &= plug_receive(s, 0, buf, ret);
		else
		    open &= plug_closing(s, NULL, 0, 0);
	    }
	} while (ret > 0);
	return open;
       case FD_ACCEPT:
	{
#ifdef NO_IPV6
	    struct sockaddr_in isa;
#else
            struct sockaddr_storage isa;
#endif
	    int addrlen = sizeof(isa);
	    SOCKET t;  /* socket of connection */

	    memset(&isa, 0, sizeof(isa));
	    err = 0;
	    t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
	    if (t == INVALID_SOCKET)
	    {
		err = p_WSAGetLastError();
		if (err == WSATRY_AGAIN)
		    break;
	    }
#ifndef NO_IPV6
            if (isa.ss_family == AF_INET &&
                s->localhost_only &&
                !ipv4_is_local_addr(((struct sockaddr_in *)&isa)->sin_addr))
#else
	    if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr))
#endif
	    {
		p_closesocket(t);      /* dodgy WinSock let nonlocal through */
	    }
	}
    }

    return 1;
}

/*
 * Call this after an operation that might have tried to send on a
 * socket, to clean up any pending network errors.
 */

__declspec(dllexport) void net_pending_errors(Actual_Socket s)
{
    /*
     * This might be a fiddly business, because it's just possible
     * that handling a pending error on one socket might cause
     * others to be closed. (I can't think of any reason this might
     * happen in current SSH implementation, but to maintain
     * generality of this network layer I'll assume the worst.)
     * 
     * So what we'll do is search the socket list for _one_ socket
     * with a pending error, and then handle it, and then search
     * the list again _from the beginning_. Repeat until we make a
     * pass with no socket errors present. That way we are
     * protected against the socket list changing under our feet.
     */

	    if (s->pending_error) {
		/*
		 * An error has occurred on this socket. Pass it to the
		 * plug.
		 */
		plug_closing(s,
			     winsock_error_string(s->pending_error),
			     s->pending_error, 0);
		}
}


__declspec(dllexport) int sk_write(Actual_Socket s, char *data, int len)
{
	return s->fn->write((Socket)s, data, len);
}

__declspec(dllexport) void sk_set_frozen(Actual_Socket s, int is_frozen) 
{
	s->fn->set_frozen((Socket)s, is_frozen);
}

__declspec(dllexport) void sk_close(Actual_Socket s)
{
	s->fn->close((Socket)s);
}


__declspec(dllexport) void sk_getaddr(SockAddr addr, wchar_t *buf, int buflen)
{
#ifndef NO_IPV6
    if (addr->ai) {
	if (p_WSAAddressToStringW) {
	    p_WSAAddressToStringW(addr->ai->ai_addr, addr->ai->ai_addrlen,
				  NULL, buf, (DWORD*)&buflen);
	} else
	    wcsncpy(buf, L"IPv6", buflen);
    } else
#endif
    if (addr->family == AF_INET) {
	struct in_addr a;
	a.s_addr = p_htonl(addr->addresses[addr->curraddr]);
	wsprintf(buf, L"%s",p_inet_ntoa(a));
	buf[buflen-1] = '\0';
    } else {
	wcsncpy(buf, addr->hostname, buflen);
	buf[buflen-1] = '\0';
    }

}

__declspec(dllexport) wchar_t *sk_addr_error(SockAddr addr)
{
    return addr->error;

}

__declspec(dllexport) void sk_addr_free(SockAddr addr)
{
#ifndef NO_IPV6
    if (addr->ais && p_freeaddrinfo)
	p_freeaddrinfo(addr->ais);
#endif
    if (addr->addresses)
	delete addr->addresses;
    delete addr;
}

__declspec(dllexport) const wchar_t *sk_socket_error(Actual_Socket s)
{
	return s->fn->socket_error((Socket)s);
}

__declspec(dllexport) WPARAM get_socket_param(Actual_Socket s)
{
	return (WPARAM)s->s;
}
#ifdef __cplusplus
}
#endif

#ifdef _MANAGED
#pragma managed(push, off)
#endif

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call) {
		case DLL_PROCESS_ATTACH:
			sk_init();
			break;
		case DLL_PROCESS_DETACH:
			sk_cleanup();
			break;
	}
    return TRUE;
}

#ifdef _MANAGED
#pragma managed(pop)
#endif

